package main

import (
	"fmt"
	uuid "github.com/satori/go.uuid"
	"github.com/spf13/viper"
	"mxshop/mxshop_api/goods_web/utils"
	consul "mxshop/mxshop_api/goods_web/utils/register"
	"os"
	"os/signal"
	"syscall"

	"go.uber.org/zap"

	"mxshop/mxshop_api/goods_web/global"
	"mxshop/mxshop_api/goods_web/initialize"
)

func main() {
	//1.初始化logger
	initialize.InitLogger()
	//3.初始化配置文件
	initialize.InitConfig()
	//3.初始化router
	Router := initialize.Routers()
	//4.初始化翻译
	if err := initialize.InitTrans("zh"); err != nil {
		panic(err)
	}
	//5.初始化srv连接
	initialize.InitSrvConn()

	viper.AutomaticEnv()
	debug := true
	if !debug {
		port, err := utils.GetFreePort()
		if err == nil {
			global.ServerConfig.Port = port
		}
	}

	register_client := consul.NewRegistryClient(global.ServerConfig.ConsulInfo.Host, global.ServerConfig.ConsulInfo.Port)
	serviceId := fmt.Sprintf("%s", uuid.NewV4())
	err := register_client.Register(utils.GetIP(), global.ServerConfig.Port, global.ServerConfig.Name, global.ServerConfig.Tags, serviceId)
	if err != nil {
		zap.S().Panic("服务注册失败：", err.Error())
	}
	/**
	1.S（）可以获取一个全局的suger
	2.日支是分级的
	3.s函数和L函数，提供了全局安全logger
	*/
	zap.S().Debugf("启动服务器，端口 ：%d", global.ServerConfig.Port)
	go func() {
		if err := Router.Run(fmt.Sprintf(":%d", global.ServerConfig.Port)); err != nil {
			zap.S().Panic("启动失败:", err.Error())
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	if err = register_client.DeRegister(serviceId); err != nil {
		zap.S().Info("注销失败：", err.Error())
	} else {
		zap.S().Info("注销成功")
	}
}
